function z = respfctAUG(x)
% function z = respfct(x)
%    this function evaluates the nonlinear residual
%    for the current balance and keff estimate
% this is the augmented nonlinear function
% which includes lambda as a variable.
% Note, x is now:
%    x(1:end-2) = currents
%    x(1:end-1) = keff
%    x(end)     = lambda

% declare the global problem variables
global ne dc sa ns sw bcL bcR gm



% compute the response matrices
M = connect(ne,bcL,bcR);
[R F A L M] = respmtx(ne, dc, sa, ns, sw, x(1:end-1) );


% compute the nonlinear function, FF(x)*x = 0
FF = [ R*M-x(end)*eye(ne*2)  zeros(ne*2,1) 
       F*M                  -sum(A*M*x(1:end-2))-sum(L)    ];  
z1 = FF*(x(1:end-1)); %
%z2 = 0.5 - 0.5*sum(x(1:end-2));

z2 = 0.5 - 0.5*x(1:end-2)'*x(1:end-2);

z  = [z1' z2']';

% if gm == 1
%     % precondition using jacobi-preconditioner
%     % Jij = dFi/dxj, so Jii = dFi/dxi,  Js = -F --> MJs = -MF
% %     m = zeros(length(x),1);
% %     m(1:end-2) = 1./(diag(R*M)-x(end));
% %     m(end-1)   = 1./(-sum(A*M*x(1:end-2))-sum(L));
% %     m(end)     = 1.;
% %     fp          = jacob('respfctAUG2',x,z);
% %     m = diag(fp);
% %     m(end)=1;
% %     mm = diag(1./m);
% fp = jacob('respfctAUG2',x,z);
% dA = diag(fp,-1); 
% dB = diag(fp,0); 
% dB(end)=1; 
% dC = diag(fp,1);
% mm = diag(dA,-1)+diag(dB)+diag(dC,1);
% mm = eye(length(x));
% z = mm\z;
% end       

